package com.hulytu.android.obfus;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;

/**
 * @author Chris (hulytu@163.com)
 * @date 2021/12/24
 */
public class StringObfuscate {

    public static String format(byte[] bytes, long seed) {
        int length = bytes.length;

        byte[] output = new byte[length];
        (new Random(seed)).nextBytes(output);

        for (int i = 0; i < length; ++i) {
            output[i] ^= bytes[i];
        }

        return new String(output, StandardCharsets.UTF_8);
    }

    public static void obfuscate(String str) throws NoSuchAlgorithmException {

        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        int length = bytes.length;
        byte[] output = new byte[length];

        long seed = SecureRandom.getInstance("SHA1PRNG").nextLong();
        new Random(seed).nextBytes(output);

        for (int i = 0; i < length; i++) {
            output[i] ^= bytes[i];
        }

        System.out.println(seed + "L => "
                + Arrays.toString(output)
                .replace("[", "{")
                .replace("]", "}")
        );
    }
}
